package com.LA_houseLease.app.custom.interceptor;

import com.LA_houseLease.common.context.BaseContext;
import com.LA_houseLease.common.context.LoginUser;
import com.LA_houseLease.common.properties.JwtProperties;
import com.LA_houseLease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
/**
 * springMVC中提供的拦截器
 * 实现了三种类型拦截器：preHandle(..)、postHandle(..)、afterCompletion(..)
 * Handler指的其实就是controller
 */
//身份校验拦截器
@Slf4j
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;

    //返回值为true则放行这个请求   为false则终止
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.warn("身份校验拦截器---preHandle..............");
        String token = request.getHeader("access-token");
        Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
        Long userId = claims.get("userId", Long.class);
        String username = claims.get("username", String.class);
        BaseContext.setLoginUser(new LoginUser(userId,username));
        //如果上一步能走完就说明校验没问题，我们下面直接返回true就可以   如果上面有问题机会直接在解密的方法里抛异常，走不到下一步
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.warn("身份校验拦截器---afterCompletion..............");
        //清理线程池
        BaseContext.clear();
    }




}
